package com.jyw.router.filter;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jyw.router.common.core.domain.CommonResult;
import com.jyw.router.common.core.redis.RedisCache;
import com.jyw.router.common.exception.constant.ExceptionCodeConstant;
import com.jyw.router.common.utils.StringUtils;
import com.jyw.router.hospital.domain.HospitalInfo;
import com.jyw.router.hospital.domain.dto.UserTokenRedisDto;
import com.jyw.router.hospital.service.IHospitalInfoService;
import com.jyw.router.hospital.service.IWxUserService;
import com.jyw.router.miniapp.service.IRouterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 沈峻
 * @ClassName RouterFilter
 * @Description TODO
 * @Date 2023/4/20 12:23
 **/
@Configuration
@WebFilter(urlPatterns = "/*", filterName = "Router")
@Slf4j
public class RouterFilter implements Filter {

    private static List<String> URLS = new ArrayList<>();
    @Resource
    private WebApplicationContext applicationContext;

    @Resource
    private IRouterService routerService;

    @Resource
    private IWxUserService wxUserService;

    @Resource
    private IHospitalInfoService hospitalInfoService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        applicationContext.getBean(RequestMappingHandlerMapping.class).getHandlerMethods().forEach((k, v) -> { k.getPatternsCondition().getPatterns().stream().forEach(s-> URLS.add(s)); });
        log.info("过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestName = request.getRequestURI();
        log.info("接收到请求:{}",request);

        /*顺手解决跨域问题*/
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

        if (URLS.contains(requestName)||!requestName.contains("/router")) {
            chain.doFilter(servletRequest, servletResponse);
        } else {
            //设置将字符以"UTF-8"编码输出到客户端浏览器
            response.setCharacterEncoding("UTF-8");
            //通过设置响应头控制浏览器以UTF-8的编码显示数据，如果不加这句话，那么浏览器显示的将是乱码
            response.setHeader("content-type", "application/json;charset=utf-8");

            String token = request.getHeader("token");
            if(!StringUtils.isEmpty(token)){
                UserTokenRedisDto redisUser = wxUserService.getUserByToken(token);
                HospitalInfo cache = hospitalInfoService.getCache(redisUser.getHospitalId());
                log.info("代理信息-用户信息:{},服务信息:{}",redisUser,cache);

                //            代理请求
                ResponseEntity<String> redirect = routerService.redirect(request, response, cache.getServerUrl(), "/router");

                response.getWriter().write(new String(redirect.getBody().getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));

                log.info("代理接口,返回数据:{}",redirect);
            }else{
                //让登录
                response.getWriter().write(JSONObject.toJSONString(CommonResult.error(ExceptionCodeConstant.TOKEN_UNAUTHORIZED,"token不存在")));
            }
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

}
